package top.luoblog.observer.withoutjdk;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : luo
 * @description : 用于记数(数量改变时通知所有观察者)
 */
public class CounterSubject implements Subject {

    private List<Observer> observers;

    private int count;

    public CounterSubject() {
        count = 0;
        observers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        int index = observers.indexOf(observer);
        if (index >= 0) {
            observers.remove(index);
        }
    }

    @Override
    public void notifyObserver(Observer observer) {
        observer.update(count);
    }

    /**
     * 改变时通知观察者
     */
    public void setCount(int count) {
        this.count = count;
        for (Observer observer : observers) {
            notifyObserver(observer);
        }
    }

}
